package org.btik.lightweb.conf;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.btik.lightweb.interceptor.DevPermissionInterceptor;
import org.btik.lightweb.interceptor.PermissionInterceptor;
import org.btik.lightweb.sensitive.SensitiveDtoResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.HashSet;
import java.util.List;
import java.util.TimeZone;

/**
 * @author lustre
 * @since 2023/6/8 10:38
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final Log log = LogFactory.getLog(WebConfig.class);

    @ConfigurationProperties(prefix = "admin.permission")
    @Configuration
    public static class AdminPermissionConf {
        private HashSet<String> urls;

        public HashSet<String> getUrls() {
            return urls;
        }

        public void setUrls(HashSet<String> urls) {
            this.urls = urls;
        }
    }

    private static final String CROSS_ORIGIN_FLAG = "light.server.CrossOrigin";

    @Value("${spring.jackson.time-zone:-}")
    private String timeZone;

    @Autowired
    private AdminPermissionConf adminPermissionUri;


    /**
     * 未设置时区时，{@link #timeZone}的默认值
     */
    private static final String NONE = "-";

    @Autowired
    private SensitiveDtoResolver sensitiveDtoResolver;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(sensitiveDtoResolver);
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        PermissionInterceptor interceptor;
        // 允许跨域的时候放行options
        if (Boolean.getBoolean(CROSS_ORIGIN_FLAG)) {
            interceptor = new DevPermissionInterceptor(adminPermissionUri.getUrls());
        } else {
            interceptor = new PermissionInterceptor(adminPermissionUri.getUrls());
        }

        registry.addInterceptor(interceptor).addPathPatterns("/**")
                .excludePathPatterns(
                        // 静态资源
                        "/index.html", "/index", "/js/**", "/css/**", "/images/**", "/error",
                        "/favicon.ico",
                        "/",
                        // 登录相关s
                        "/login/doLogin", "/login/captcha", "/login/iLogin",
                        "/sensitiveData/exchangeRequest");

    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        if (!Boolean.getBoolean(CROSS_ORIGIN_FLAG)) {
            return;
        }
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST")
                .allowedHeaders("*")
                .allowCredentials(true);

    }

    /**
     * 当未指定jackson时区的时候，使用默认时区而非0时区
     */
    @Bean
    public TimeZone dateFormatTimeZone(JacksonProperties jacksonProperties) {
        if (NONE.equals(timeZone)) {
            TimeZone deafultTimeZone = TimeZone.getDefault();
            log.info("DateFormat's time zone is not specified and now assumes the default time zone:  " + deafultTimeZone);
            jacksonProperties.setTimeZone(deafultTimeZone);
            return deafultTimeZone;
        }
        TimeZone timeZone = jacksonProperties.getTimeZone();
        log.info("The time zone for DateFormat is " + timeZone);

        return timeZone;
    }


}